from museumweb.mainpage.models import Profile, Painting, Code
from django.contrib import admin
from django.contrib.auth.models import User

class ProfileAdmin(admin.ModelAdmin):
    list_display = ['username','first','last','email','museum']
    search_fields = ['username','museum']
    def queryset(self,request):
        qs = super(ProfileAdmin,self).queryset(request)
        the_user = request.user
        user_prof = Profile.objects.get(user=the_user)
        museum = user_prof.museum
        if not the_user.is_superuser:
            qs = qs.filter(museum=museum)
        return qs
class PaintingAdmin(admin.ModelAdmin):
    list_display = ['name','artist','file','museum']
    search_fields = ['name','artist']    
    #readonly_fields = ['user']
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "museum":
            kwargs['queryset'] = Profile.objects.filter(username=request.user.username)
            p = Profile.objects.get(username=request.user.username)
            kwargs['initial'] = p.museum
            return db_field.formfield(**kwargs)
    
    def queryset(self,request):
        qs = super(PaintingAdmin,self).queryset(request)
        the_user = request.user
        user_prof = Profile.objects.get(username=request.user.username)
        if not the_user.is_superuser:
            qs = qs.filter(museum=user_prof)
        return qs
    
class CodeAdmin(admin.ModelAdmin):
    list_display = ['museum','code']
    search_fields = ['museum'] 
        
admin.site.register(Profile, ProfileAdmin)
admin.site.register(Painting,PaintingAdmin)
admin.site.register(Code,CodeAdmin)
